import json
import re
from requests_html import requests, HTMLSession, HtmlElement


class AttrDict(dict):
    def __getattr__(self, name):
        return self.__getitem__(name)


api = AttrDict(
    {
        "search": "https://fundsuggest.eastmoney.com/FundSearch/api/FundSearchAPI.ashx",
        "filter": "http://fund.eastmoney.com/data/FundGuideapi.aspx",
        "jjjz": "http://fundgz.1234567.com.cn/js/{code}.js",
        "detail": "http://fund.eastmoney.com/{code}.html",
        "picture": "http://j4.dfcfw.com/charts/pic6/{code}.png?v=20220224162206",
        "jz_picture": "http://j3.dfcfw.com/images/JJJZ1/{code}.png",
        "ljsylzs": "http://api.fund.eastmoney.com/pinzhong/LJSYLZS?fundCode={code}&indexcode=000300&type={type}",
        "javascript": "http://fund.eastmoney.com/pingzhongdata/{code}.js?v=20220225095519",
        "jbxx": "http://api.fund.eastmoney.com/FundCompare/JBXX?bzdm={code}",
        "yjpjbj": "http://api.fund.eastmoney.com/FundCompare/YJPJBJ?bzdm={code}",
        "ljsyl": "http://api.fund.eastmoney.com/FundCompare/LJSYL?bzdm={code}&c={c}",
    }
)


def search(key):
    params = {"m": 1, "key": key}
    res = requests.get(api.search, params=params)
    return res.json()["Datas"]
# [{'_id': '005219', 'CODE': '005219', 'NAME': '华夏聚惠(FOF)C', 'JP': 'HXJHFOFC', 'CATEGORY': 700, 'CATEGORYDESC': '基金', 'STOCKMARKET': None, 'BACKCODE': '005219', 'MatchCount': 1, 
# 'FundBaseInfo':
#  {'_id': '005219', 'FCODE': '005219', 'NAVURL': 'http://fund.eastmoney.com/HH_jzzzl.html#os_0;isall_0;ft_;pt_3', 'SHORTNAME': '华夏聚惠(FOF)C', 'JJGSID': '80000222', 'JJGS': '华夏基金', 'JJJLID': '30767260', 'JJJL': '卢 少强', 'FUNDTYPE': '002', 'ISBUY': '1', 'FTYPE': 'FOF', 'MINSG': 10.0, 'JJGSBID': 5.0, 'OTHERNAME': '华夏聚惠C,华夏聚惠稳健目标风险混合型基金中基金(FOF)C', 'FSRQ': '2023-04-28', 'DWJZ': 1.288}, 'StockHolder': None, 'ZTJJInfo': [], 'SEARCHWEIGHT': 0.0},
#  {'_id': 'D60066', 'CODE': 'D60066', 'NAME': '华鑫鑫智FOF', 'JP': 'HXXZFOF', 'CATEGORY': 750, 'CATEGORYDESC': '高端理财', 'STOCKMARKET': None, 'BACKCODE': 'D60066', 'MatchCount': 1, 'FundBaseInfo': None, 'StockHolder': None, 'ZTJJInfo': None, 'SEARCHWEIGHT': 2.0},
#  {'_id': 'DS0005', 'CODE': 'DS0005', 'NAME': '鼎实FOF五期', 'JP': 'DSFOFWQ', 'CATEGORY': 750, 'CATEGORYDESC': '高端理财', 'STOCKMARKET': None, 'BACKCODE': 'DS0005', 'MatchCount': 1, 'FundBaseInfo': None, 'StockHolder': None, 'ZTJJInfo': None, 'SEARCHWEIGHT': 2.0},
#  {'_id': 'SS0476', 'CODE': 'SS0476', 'NAME': '恒泰龍FOF1号', 'JP': 'HTLFOF1H', 'CATEGORY': 750, 'CATEGORYDESC': '高端理财', 'STOCKMARKET': None, 'BACKCODE': 'SS0476', 'MatchCount': 1, 'FundBaseInfo': None, 'StockHolder': None, 'ZTJJInfo': None, 'SEARCHWEIGHT': 2.0}, 
#  {'_id': 'SSR809', 'CODE': 'SSR809', 'NAME': '中泰星益1号FOF', 'JP': 'ZTXY1HFOF', 'CATEGORY': 750, 'CATEGORYDESC': '高端理财', 'STOCKMARKET': None, 'BACKCODE': 'SSR809', 'MatchCount': 1, 'FundBaseInfo': None, 'StockHolder': None, 'ZTJJInfo': None, 'SEARCHWEIGHT': 2.0},
#  {'_id': 'SSX487', 'CODE': 'SSX487', 'NAME': '中泰星益3号FOF', 'JP': 'ZTXY3HFOF', 'CATEGORY': 750, 'CATEGORYDESC': '高端理财', 'STOCKMARKET': None, 'BACKCODE': 'SSX487', 'MatchCount': 1, 'FundBaseInfo': None, 'StockHolder': None, 'ZTJJInfo': None, 'SEARCHWEIGHT': 2.0},
#  {'_id': 'SJE919', 'CODE': 'SJE919', 'NAME': '洪运瑞恒泰和FOF', 'JP': 'HYRHTHFOF', 'CATEGORY': 750, 'CATEGORYDESC': '高端理财', 'STOCKMARKET': None, 'BACKCODE': 'SJE919', 'MatchCount': 1, 'FundBaseInfo': None, 'StockHolder': None, 'ZTJJInfo': None, 'SEARCHWEIGHT': 2.0},
#  {'_id': 'SSX488', 'CODE': 'SSX488', 'NAME': '中泰星益5号FOF', 'JP': 'ZTXY5HFOF', 'CATEGORY': 750, 'CATEGORYDESC': '高端理财', 'STOCKMARKET': None, 'BACKCODE': 'SSX488', 'MatchCount': 1, 'FundBaseInfo': None, 'StockHolder': None, 'ZTJJInfo': None, 'SEARCHWEIGHT': 2.0},
#  {'_id': 'YHZH01', 'CODE': 'YHZH01', 'NAME': '银河智汇FOF1号', 'JP': 'YHZHFOF1H', 'CATEGORY': 750, 'CATEGORYDESC': '高端理财', 'STOCKMARKET': None, 'BACKCODE': 'YHZH01', 'MatchCount': 1, 'FundBaseInfo': None, 'StockHolder': None, 'ZTJJInfo': None, 'SEARCHWEIGHT': 2.0},
#  {'_id': 'SJB925', 'CODE': 'SJB925', 'NAME': '华泰期货FOF2号', 'JP': 'HTQHFOF2H', 'CATEGORY': 750, 'CATEGORYDESC': '高端理财', 'STOCKMARKET': None, 'BACKCODE': 'SJB925', 'MatchCount': 1, 'FundBaseInfo': None, 'StockHolder': None, 'ZTJJInfo': None, 'SEARCHWEIGHT': 2.0}]

tps = {
    "软件开发": "801104",
    "航天装备": "801741",
    "云计算": "861060",
    "IT服务": "801103",
    "计算机": "801750",
    "通信": "801770",
    "通信设备": "801102",
    "其他电源设备": "801733",
    "5G概念": "861183",
    "华为概念": "861258",
    "传媒": "801760",
    "元宇宙概念": "861399",
    "中芯概念": "861331",
    "国产芯片": "861205",
    "物联网": "861045",
    "中字头": "861013",
    "充电桩": "861169",
    "储能": "861380",
    "军工": "861001",
    "特斯拉": "861120",
    "深圳特区": "861040",
    "航空机场": "801991",
    "新能源车": "861206",
    "军民融合": "861220",
    "国企改革": "861153",
    "电商概念": "861137",
    "QFII重仓": "861034",
    "影视概念": "861251",
    "预亏预减": "861053",
    "元件": "801083",
    "白酒": "801125",
    "通用设备": "801072",
    "贵金属": "801053",
    "机构重仓": "861043",
    "机械设备": "801890",
    "跨境支付": "861434",
    "富时罗素": "861271",
    "标准普尔": "861282",
    "贬值受益": "861222",
    "新能源": "861004",
    "黄金概念": "861038",
    "央视50": "861089",
    "风能": "861075",
    "证金持股": "861187",
    "上证380": "861174",
    "融资融券": "861076",
    "食品饮料": "801120",
    "转债标的": "861032",
    "深股通": "861216",
    "AH股": "861008",
    "新材料": "861028",
    "中证500": "861170",
    "美容护理": "801980",
    "沪股通": "861176",
    "超级品牌": "861221",
    "大飞机": "861224",
    "消费电子": "801085",
    "预盈预增": "861054",
    "化妆品概念": "861366",
    "家用电器": "801110",
    "通用航空": "861102",
    "专用设备": "801074",
    "互联金融": "861113",
    "汽车": "801880",
    "汽车零部件": "801093",
    "深成500": "861051",
    "稀缺资源": "861024",
    "基础建设": "801723",
    "茅指数": "861389",
    "HS300": "861009",
    "国防军工": "801740",
    "养老概念": "861122",
    "锂电池": "861057",
    "乡村振兴": "861240",
    "猪肉概念": "861204",
    "基金重仓": "861035",
    "中药概念": "861094",
    "医疗美容": "861290",
    "MSCI中国": "861230",
    "乘用车": "801095",
    "建筑装饰": "801720",
    "交通运输": "801170",
    "中药": "801155",
    "上证180": "861091",
    "电子": "801080",
    "农业种植": "861289",
    "商业贸易": "801200",
    "白色家电": "801111",
    "公用事业": "801160",
    "流感": "861305",
    "固态电池": "861361",
    "盐湖提锂": "861378",
    "券商概念": "861180",
    "创业成份": "861114",
    "保险": "801194",
    "光伏设备": "801735",
    "非银金融": "801790",
    "化学制品": "801034",
    "证券": "801193",
    "上证50": "861090",
    "化学制药": "801151",
    "转基因": "861306",
    "航空装备": "801742",
    "百元股": "861422",
    "小金属": "801054",
    "煤化工": "861003",
    "煤炭": "801950",
    "半导体": "801081",
    "基础化工": "801030",
    "有色金属": "801050",
    "环保": "801970",
    "宁组合": "861390",
    "农林牧渔": "801010",
    "医药生物": "801150",
    "医疗器械": "801153",
    "装修建材": "801713",
    "电力设备": "801730",
    "化学原料": "801033",
    "钢铁": "801040",
    "建筑材料": "801710",
    "银行": "801780",
    "CRO": "861299",
    "医疗服务": "801156",
    "生物制品": "801152",
    "能源金属": "801056",
    "房地产开发": "801181",
    "房地产": "801180",
    "电池": "801737",
}


def filter_(currentPage=1, pageSize=20, ft=None, rs=None, tp=None, **kw):
    params = {
        "rs": rs,  # "rs: 3y,20" 基金业绩 时间单位,排名
        "tp": tp,  # 基金主题
        "ft": ft,  # gp,hh,zq,zs,qdii,fof
        "dt": "4",
        "sc": "3y",
        "st": "desc",
        "pi": currentPage,
        "pn": pageSize,
        "zf": "diy",
        "sh": "list",
    }
    res = requests.get(api.filter, params=params)
    text = res.text.replace("var rankData =", "", 1)
    data = json.loads(text)

    res = {
        "total": int(data["datacount"]),
        "totalPages": int(data["allPages"]),
        "pageSize": int(data["pageNum"]),
        "currentPage": int(data["pageIndex"]),
        "datas": [],
    }
    # 'total': 12917, 'totalPages': 646, 'pageSize': 20, 'currentPage': 1, 'datas': [{},{},{}]
    # 25 fields
    keys = [
        "code",
        "name",
        "jjjp",  # 简拼
        "type",
        "yt",  # 今年来
        "w1",  # 近一周
        "m1",  # 近一月
        "m3",
        "m6",
        "y1",  # 近一年
        "y2",
        "y3",
        "12_",
        "13_",
        "14_",
        "date",
        "netv",  # 净值
        "rate",  # 日增长率
        "18_",
        "charge",  # 折扣手续费
        "min",  # 购买起点
        "charge2",  # 原手续费
        "22_",
        "fn",  # 成立以来
    ]
    for i in data["datas"]:
        values = i.split(",")
        res["datas"].append(dict(zip(keys, values))) #zip()函数创建字典
    return res
        # {'code': '016314', 'name': '同泰泰裕三个月定开债A', 'jjjp': 'TTTYSGYDKZA', 'type': '债券型-长债', 'yt': '55.94', 'w1': '0', 'm1': '55.78', 'm3': '55.98', 'm6': '',
    #  'y1': '', 'y2': '', 'y3': '', '12_': '', '13_': '', '14_': '1', 'date': '2023-03-17', 'netv': '1.56', 'rate': '0', '18_': '0', 'charge': '0.03%', 'min': '10',
    #  'charge2': '1', '22_': '0.30%', 'fn': '0.03%'}


def get_jz(code):
    try:
        # 净值、估值
        res = requests.get(api.jjjz.format(code=code))
        text = re.search(r"jsonpgz\((.*)\)", res.text).group(1)
        data = json.loads(text)
        return data
    except:
        return {
            "fundcode": code,
            "name": None,
            "jzrq": None,  # 净值日期
            "dwjz": None,  # 单位净值
            "gsz": None,  # 估算值
            "gszzl": None,  # 估算增长率
            "gztime": None,  # 估值时间
        }


def css_find_text(html: HtmlElement, sel: str, **kw):
    el = html.find(sel, first=True)
    if el:
        return el.text


def get_storage(data, html: HtmlElement):
    # 持仓
    stock10 = {
        "data": [],
        "sum": None,
        "end_date": None,
    }
    for i in html.find(
        "#position_shares > div.poptableWrap > table > tr:nth-child(1) ~ tr"
    ):
        d = [i.text for i in i.find("td")][:3]
        if len(d) == 3:
            stock10["data"].append(d)
    stock10["sum"] = css_find_text(
        html, "#position_shares > div.poptableWrap > p > span.sum-num", first=True
    )
    stock10["end_date"] = html.find(
        "#position_shares > div.poptableWrap_footer > span", first=True
    ).text
    data["stock10"] = stock10

    # 债券
    bond10 = {
        "data": [],
        "sum": None,
    }
    for i in html.find(
        "#position_bonds > div.poptableWrap > table > tr:nth-child(1) ~ tr"
    ):
        d = [i.text for i in i.find("td")][:2]
        if len(d) == 2:
            bond10["data"].append(d)
    bond10["sum"] = css_find_text(
        html, "#position_bonds > div.poptableWrap > p > span.sum-num", first=True
    )
    bond10["end_date"] = html.find(
        "#position_bonds > div.poptableWrap_footer > span", first=True
    ).text

    data["bond10"] = bond10


def get_jz_history(data, html: HtmlElement):
    jzhistory = []
    for i in html.find(
        "#Li1 > div.poptableWrap.singleStyleHeight01 > table > tr:nth-child(1) ~ tr"
    ):
        d = [i.text for i in i.find("td")][:4]
        jzhistory.append(d)
    data["jzhistory"] = jzhistory


def detail(code):
    data = get_jz(code)
    session = HTMLSession()
    res = session.get(api.detail.format(code=code))
    html: HtmlElement = res.html
    if data["name"] is None:
        # qdii
        data["name"] = html.find("span.funCur-FundName", first=True).text
        data["jzrq"] = re.search(
            r"\d{4}\-\d{2}\-\d{2}",
            html.find("div.dataOfFund > dl.dataItem02 > dt > p", first=True).text,
        ).group()
        data["dwjz"] = html.find(
            "div.dataOfFund > dl.dataItem02 > dd.dataNums > span:nth-child(1)",
            first=True,
        ).text

    data["ljjz"] = html.find(
        "dl.dataItem03 > dd.dataNums > span", first=True
    ).text  # 累计净值
    data["m1"] = html.find(
        "dl.dataItem01 > dd:nth-child(3) > span:nth-child(2)",
        first=True,
    ).text  # 近一月
    data["m3"] = html.find(
        "dl.dataItem02 > dd:nth-child(3) > span:nth-child(2)",
        first=True,
    ).text
    data["m6"] = html.find(
        "dl.dataItem03 > dd:nth-child(3) > span:nth-child(2)",
        first=True,
    ).text
    data["y1"] = html.find(
        "dl.dataItem01 > dd:nth-child(4) > span:nth-child(2)",
        first=True,
    ).text
    data["y3"] = html.find(
        "dl.dataItem02 > dd:nth-child(4) > span:nth-child(2)",
        first=True,
    ).text
    data["fn"] = html.find(
        "dl.dataItem03 > dd:nth-child(4) > span:nth-child(2)",
        first=True,
    ).text
    data["type"] = html.find(
        "div.fundInfoItem > div.infoOfFund > table > tr:nth-child(1) > td:nth-child(1) > a",
        first=True,
    ).text
    data["scale"] = html.find(
        "div.fundInfoItem > div.infoOfFund > table  > tr:nth-child(1) > td:nth-child(2)",
        first=True,
    ).text.replace("基金规模：", "")
    data["manager"] = html.find(
        "div.fundInfoItem > div.infoOfFund > table  > tr:nth-child(1) > td:nth-child(3) > a",
        first=True,
    ).text
    data["fn_date"] = html.find(
        "div.fundInfoItem > div.infoOfFund > table  > tr:nth-child(2) > td:nth-child(1)",
        first=True,
    ).text.replace("成 立 日：", "")
    data["company"] = html.find(
        "div.fundInfoItem > div.infoOfFund > table > tr:nth-child(2) > td:nth-child(2) > a",
        first=True,
    ).text
    # data["rank"] = html.find(
    #     "div.jjpj",
    #     first=True,
    # ).text
    {
        "fundcode": "005477",
        "name": "长安鑫禧灵活配置混合A",
        "jzrq": "2022-02-23",
        "dwjz": "0.8267",
        "gsz": "0.8020",
        "gszzl": "-2.98",
        "gztime": "2022-02-24 15:00",
        "ljjz": "0.8267",
        "m1": "25.85%",
        "m3": "2.75%",
        "m6": "-10.45%",
        "y1": "-20.76%",
        "y3": "-9.22%",
        "fn": "-17.33%",
        "type": "混合型-灵活",
        "scale": "0.62亿元（2021-12-31）",
        "manager": "袁苇",
        "fn_date": "2018-02-07",
        # "company": "暂无评级",
    }
    get_storage(data, html)
    get_jz_history(data, html)
    return data


def get_picture(code):
    # 盘中实时净值估算图
    res = requests.get(api.picture.format(code=code))
    # from django.http import StreamingHttpResponse
    # return HttpResponse(content, content_type='image/png')
    return res.content


def get_jz_picture(code):
    # 净值走势图
    res = requests.get(api.jz_picture.format(code=code))
    # from django.http import StreamingHttpResponse
    # return HttpResponse(content, content_type='image/png')
    return res.content


def get_ljsylzs(code, type="m6"):
    # 累计收益率走势
    maps = {
        "m1": "m",
        "m3": "q",
        "m6": "hy",
        "y1": "y",
        "y3": "try",
        "y5": "fiy",
        "yt": "sy",  # 今年来
        "max": "se",  # 最大
    }
    # referer反爬
    res = requests.get(
        api.ljsylzs.format(code=code, type=maps[type]),
        headers={"Referer": "http://fund.eastmoney.com/"},
    )
    return res.json()["Data"]
    # print(res.text)
    # {"Data":[{"data":[[1667491200000.0,0.0],[1667750400000.0,1.73],[1667836800000.0,2.55],[1667923200000.0,2.20],[1668009600000.0,-1.16],[1668096000000.0,-1.21],[1668355200000.0,-4.63],[1668441600000.0,-3.70],[1668528000000.0,-5.78],[1668614400000.0,-6.51],[1668700800000.0,-8.80],[1668960000000.0,-7.94],[1669046400000.0,-10.00],[1669132800000.0,-9.26],[1669219200000.0,-8.79],[1669305600000.0,-10.86],[1669564800000.0,-11.96],[1669651200000.0,-12.14],[1669737600000.0,-9.96],[1669824000000.0,-10.54],[1669910400000.0,-11.66],[1670169600000.0,-12.74],[1670256000000.0,-12.47],[1670342400000.0,-11.94],[1670428800000.0,-12.73],[1670515200000.0,-12.39],[1670774400000.0,-15.00],[1670860800000.0,-15.68],[1670947200000.0,-16.37],[1671033600000.0,-15.37],[1671120000000.0,-17.61],[1671379200000.0,-16.25],[1671465600000.0,-17.87],[1671552000000.0,-18.32],[1671638400000.0,-21.01],[1671724800000.0,-20.85],[1671984000000.0,-19.23],[1672070400000.0,-18.87],[1672156800000.0,-20.09],[1672243200000.0,-20.64],[1672329600000.0,-21.94],[1672416000000.0,-21.94],[1672675200000.0,-19.89],[1672761600000.0,-21.85],[1672848000000.0,-20.02],[1672934400000.0,-17.95],[1673193600000.0,-17.55],[1673280000000.0,-16.95],[1673366400000.0,-18.35],[1673452800000.0,-17.46],[1673539200000.0,-17.52],[1673798400000.0,-15.99],[1673884800000.0,-16.07],[1673971200000.0,-15.33],[1674057600000.0,-15.49],[1674144000000.0,-12.61],[1675008000000.0,-11.34],[1675094400000.0,-11.32],[1675180800000.0,-10.29],[1675267200000.0,-11.35],[1675353600000.0,-12.12],[1675612800000.0,-13.26],[1675699200000.0,-13.18],[1675785600000.0,-12.28],[1675872000000.0,-12.39],[1675958400000.0,-14.34],[1676217600000.0,-14.48],[1676304000000.0,-14.80],[1676390400000.0,-15.99],[1676476800000.0,-18.05],[1676563200000.0,-18.94],[1676822400000.0,-19.00],[1676908800000.0,-18.31],[1676995200000.0,-19.20],[1677081600000.0,-18.65],[1677168000000.0,-19.16],[1677427200000.0,-18.53],[1677513600000.0,-18.85],[1677600000000.0,-18.91],[1677686400000.0,-20.37],[1677772800000.0,-20.51],[1678032000000.0,-20.05],[1678118400000.0,-21.37],[1678204800000.0,-21.27],[1678291200000.0,-21.09],[1678377600000.0,-22.73],[1678636800000.0,-23.74],[1678723200000.0,-23.96],[1678809600000.0,-24.49],[1678896000000.0,-26.69],[1678982400000.0,-26.28],[1679241600000.0,-26.38],[1679328000000.0,-24.22],[1679414400000.0,-24.62],[1679500800000.0,-25.12],[1679587200000.0,-25.75],[1679846400000.0,-26.31],[1679932800000.0,-27.88],[1680019200000.0,-27.87],[1680105600000.0,-27.36],[1680192000000.0,-27.65],[1680451200000.0,-25.87],[1680537600000.0,-27.94],[1680710400000.0,-28.59],[1680796800000.0,-29.01],[1681056000000.0,-28.15],[1681142400000.0,-26.76],[1681228800000.0,-27.72],[1681315200000.0,-28.82],[1681401600000.0,-25.60],[1681660800000.0,-25.14],[1681747200000.0,-24.81],[1681833600000.0,-25.03],[1681920000000.0,-27.02],[1682006400000.0,-28.72],[1682265600000.0,-28.24],[1682352000000.0,-32.20],[1682438400000.0,-30.30],[1682524800000.0,-30.77],[1682611200000.0,-30.70],[1683129600000.0,-30.49],[1683216000000.0,-31.74]],"name":"长安鑫禧灵活配置混合A"},{"data":[[1667491200000.0,0.0],[1667750400000.0,-0.28],[1667836800000.0,-0.69],[1667923200000.0,-1.19],[1668009600000.0,-2.12],[1668096000000.0,-1.14],[1668355200000.0,-1.73],[1668441600000.0,-0.31],[1668528000000.0,-1.01],[1668614400000.0,-1.16],[1668700800000.0,-1.56],[1668960000000.0,-1.60],[1669046400000.0,-2.44],[1669132800000.0,-2.38],[1669219200000.0,-2.33],[1669305600000.0,-2.95],[1669564800000.0,-3.27],[1669651200000.0,-2.19],[1669737600000.0,-2.19],[1669824000000.0,-1.36],[1669910400000.0,-1.58],[1670169600000.0,-1.33],[1670256000000.0,-1.18],[1670342400000.0,-1.37],[1670428800000.0,-1.43],[1670515200000.0,-1.09],[1670774400000.0,-1.50],[1670860800000.0,-2.18],[1670947200000.0,-2.21],[1671033600000.0,-2.07],[1671120000000.0,-2.68],[1671379200000.0,-3.65],[1671465600000.0,-4.49],[1671552000000.0,-4.79],[1671638400000.0,-5.11],[1671724800000.0,-5.46],[1671984000000.0,-4.21],[1672070400000.0,-3.30],[1672156800000.0,-3.66],[1672243200000.0,-3.62],[1672329600000.0,-3.47],[1672416000000.0,-3.47],[1672675200000.0,-2.45],[1672761600000.0,-2.48],[1672848000000.0,-1.29],[1672934400000.0,-1.02],[1673193600000.0,-0.63],[1673280000000.0,-0.43],[1673366400000.0,-0.92],[1673452800000.0,-0.91],[1673539200000.0,-0.41],[1673798400000.0,0.40],[1673884800000.0,0.46],[1673971200000.0,0.45],[1674057600000.0,1.02],[1674144000000.0,1.48],[1675008000000.0,1.87],[1675094400000.0,1.36],[1675180800000.0,2.15],[1675267200000.0,2.25],[1675353600000.0,1.93],[1675612800000.0,1.14],[1675699200000.0,1.13],[1675785600000.0,0.75],[1675872000000.0,1.93],[1675958400000.0,1.39],[1676217600000.0,2.21],[1676304000000.0,2.13],[1676390400000.0,1.90],[1676476800000.0,0.89],[1676563200000.0,-0.10],[1676822400000.0,1.15],[1676908800000.0,1.17],[1676995200000.0,0.96],[1677081600000.0,0.90],[1677168000000.0,0.36],[1677427200000.0,0.10],[1677513600000.0,0.47],[1677600000000.0,1.09],[1677686400000.0,0.63],[1677772800000.0,0.62],[1678032000000.0,0.90],[1678118400000.0,-0.42],[1678204800000.0,-0.45],[1678291200000.0,-0.56],[1678377600000.0,-1.47],[1678636800000.0,-0.77],[1678723200000.0,-1.38],[1678809600000.0,-1.46],[1678896000000.0,-2.54],[1678982400000.0,-2.29],[1679241600000.0,-2.61],[1679328000000.0,-1.68],[1679414400000.0,-1.47],[1679500800000.0,-0.96],[1679587200000.0,-1.08],[1679846400000.0,-1.07],[1679932800000.0,-1.51],[1680019200000.0,-1.30],[1680105600000.0,-0.96],[1680192000000.0,-0.34],[1680451200000.0,0.55],[1680537600000.0,0.45],[1680710400000.0,0.65],[1680796800000.0,1.39],[1681056000000.0,0.59],[1681142400000.0,0.56],[1681228800000.0,0.76],[1681315200000.0,0.12],[1681401600000.0,0.64],[1681660800000.0,0.97],[1681747200000.0,0.99],[1681833600000.0,0.58],[1681920000000.0,0.74],[1682006400000.0,-1.07],[1682265600000.0,-1.80],[1682352000000.0,-2.50],[1682438400000.0,-2.42],[1682524800000.0,-2.36],[1682611200000.0,-1.45],[1683129600000.0,-1.66],[1683216000000.0,-2.39]],"name":"同类平均"},{"data":[[1667491200000.0,0.0],[1667750400000.0,0.22],[1667836800000.0,-0.47],[1667923200000.0,-1.40],[1668009600000.0,-2.16],[1668096000000.0,0.56],[1668355200000.0,0.71],[1668441600000.0,2.62],[1668528000000.0,1.78],[1668614400000.0,1.37],[1668700800000.0,0.91],[1668960000000.0,0.05],[1669046400000.0,0.06],[1669132800000.0,0.17],[1669219200000.0,-0.28],[1669305600000.0,0.23],[1669564800000.0,-0.90],[1669651200000.0,2.16],[1669737600000.0,2.28],[1669824000000.0,3.39],[1669910400000.0,2.75],[1670169600000.0,4.77],[1670256000000.0,5.34],[1670342400000.0,5.08],[1670428800000.0,5.10],[1670515200000.0,6.13],[1670774400000.0,4.94],[1670860800000.0,4.74],[1670947200000.0,4.98],[1671033600000.0,4.91],[1671120000000.0,4.97],[1671379200000.0,3.35],[1671465600000.0,1.64],[1671552000000.0,1.68],[1671638400000.0,1.83],[1671724800000.0,1.62],[1671984000000.0,2.03],[1672070400000.0,3.20],[1672156800000.0,2.76],[1672243200000.0,2.38],[1672329600000.0,2.77],[1672416000000.0,2.77],[1672675200000.0,3.20],[1672761600000.0,3.34],[1672848000000.0,5.35],[1672934400000.0,5.67],[1673193600000.0,6.53],[1673280000000.0,6.64],[1673366400000.0,6.45],[1673452800000.0,6.65],[1673539200000.0,8.15],[1673798400000.0,9.84],[1673884800000.0,9.82],[1673971200000.0,9.64],[1674057600000.0,10.32],[1674144000000.0,11.00],[1675008000000.0,11.53],[1675094400000.0,10.34],[1675180800000.0,11.38],[1675267200000.0,10.99],[1675353600000.0,9.94],[1675612800000.0,8.49],[1675699200000.0,8.68],[1675785600000.0,8.20],[1675872000000.0,9.65],[1675958400000.0,9.00],[1676217600000.0,9.99],[1676304000000.0,10.04],[1676390400000.0,9.46],[1676476800000.0,8.66],[1676563200000.0,7.10],[1676822400000.0,9.72],[1676908800000.0,10.01],[1676995200000.0,9.02],[1677081600000.0,8.93],[1677168000000.0,7.80],[1677427200000.0,7.34],[1677513600000.0,8.02],[1677600000000.0,9.55],[1677686400000.0,9.31],[1677772800000.0,9.65],[1678032000000.0,9.07],[1678118400000.0,7.48],[1678204800000.0,7.09],[1678291200000.0,6.71],[1678377600000.0,5.31],[1678636800000.0,6.41],[1678723200000.0,5.77],[1678809600000.0,5.83],[1678896000000.0,4.57],[1678982400000.0,5.09],[1679241600000.0,4.56],[1679328000000.0,5.71],[1679414400000.0,6.17],[1679500800000.0,7.22],[1679587200000.0,6.90],[1679846400000.0,6.51],[1679932800000.0,6.17],[1680019200000.0,6.34],[1680105600000.0,7.20],[1680192000000.0,7.53],[1680451200000.0,8.58],[1680537600000.0,8.92],[1680710400000.0,8.75],[1680796800000.0,9.45],[1681056000000.0,8.96],[1681142400000.0,8.84],[1681228800000.0,8.76],[1681315200000.0,8.01],[1681401600000.0,8.62],[1681660800000.0,10.15],[1681747200000.0,10.48],[1681833600000.0,9.49],[1681920000000.0,9.18],[1682006400000.0,7.04],[1682265600000.0,5.72],[1682352000000.0,5.19],[1682438400000.0,5.10],[1682524800000.0,5.87],[1682611200000.0,6.95],[1683129600000.0,6.98],[1683216000000.0,6.63]],"name":"沪深300"}],"ErrCode":0,"ErrMsg":null,"TotalCount":0,"Expansion":null,"PageSize":0,"PageIndex":0}

def get_js_data(code):
    res = requests.get(api.javascript.format(code=code))
    return res.text
    # print(res.text)
    # http://fund.eastmoney.com/pingzhongdata/005477.js?v=20220225095519


def get_jbxx(code):
    res = requests.get(
        api.jbxx.format(code=code),
        headers={"Referer": "http://fund.eastmoney.com/"},
    )
    data = res.json()["Data"]
    data = json.loads(data)
    keys = [
        "code",
        "name",
        "jjjp",  # 简拼
        "type",
        "pzgz",  # 盘中估值
        "gzzf",  # 估值涨幅
        "jz",  # 最新单位净值
        "jzrq",  # 净值日期
        "ljjz",  # 累计净值
        "rzzl",  # 日增长率
        "sqdwjz",  # 上期单位净值
        "sqjzrq",  # 上期单位净值
        "manager",  # 基金经理
        "13_",
        "company",  # 基金公司
        "15_",
    ]
    return [dict(zip(keys, i.split(","))) for i in data]
    # print([dict(zip(keys, i.split(","))) for i in data])
#[{'code': '161725', 'name': '招商中证白酒指数(LOF)A', 'jjjp': 'ZSZZBJZSLOFA', 
# 'type': '指数型-股票', 'pzgz': '1.1231', 'gzzf': '1.06', 'jz': '1.1231', 'jzrq': '2023-05-05', 'ljjz': '2.8392', 'rzzl': '1.06', 'sqdwjz': '1.1113', 'sqjzrq': '2023-05-04', 'manager': '侯昊', '13_': '30379533', 'company': '招商基金', '15_': '80036782'}, {'code': '202801', 'name': '南方全球精选配置', 'jjjp': 'NFQQJXPZ', 'type': 'QDII', 'pzgz': '', 'gzzf': '', 'jz': '0.8520', 'jzrq': '2023-05-04', 'ljjz': '0.9930', 'rzzl': '-1.62', 'sqdwjz': '0.8660', 'sqjzrq': '2023-04-28', 'manager': '黄亮', '13_': '30042438', 'company': '南方基金', '15_': '80000220'}]

def get_yjpjbj(code):
    res = requests.get(
        api.yjpjbj.format(code=code),
        headers={"Referer": "http://fund.eastmoney.com/"},
    )
    data = res.json()["Data"]
    data = json.loads(data)["jdsy"]
    keys = [
        "code",
        "name",
        "date",  # 成立日期
        "yt",  # 今年来
        "w1",  # 近一周
        "m1",  # 近一月
        "m3",
        "m6",
        "y1",  # 近一年
        "y2",
        "y3",
        "y5",
        "fn",  # 成立以来
    ]
    return [dict(zip(keys, i.split(","))) for i in data]
    # print([dict(zip(keys, i.split(","))) for i in data])
    # [{'code': '161725', 
    # 'name': '招商中证白酒指数(LOF)A', 
    # 'date': '2015-05-27', 'yt': '-2.53%', 
    # 'w1': '-0.16%', 'm1': '-9.45%', 'm3': '-8.79%', 'm6': '12.92%', 'y1': '2.87%', 'y2': '-15.35%', 'y3': '85.03%', 'y5': '162.06%', 'fn': '354.25%'}, {'code': '202801', 'name': '南 方全球精选配置', 'date': '2007-09-19', 'yt': '-3.18%', 'w1': '-1.05%', 'm1': '-3.18%', 'm3': '-7.29%', 'm6': '2.77%', 'y1': '-3.29%', 'y2': '-28.04%', 'y3': '-6.23%', 'y5': '8.73%', 'fn': '-3.45%'}]

def get_ljsyl(code, c="month"):
    m = {
        "week": "近1周",
        "month": "近1月",
        "threemonth": "近3月",
        "sixmonth": "近6月",
        "year": "近1年",
        "twoyear": "近2年",
        "threeyear": "近3年",
    }
    res = requests.get(
        api.ljsyl.format(code=code, c=c),
        headers={"Referer": "http://fund.eastmoney.com/"},
    )
    data = res.json()["Data"]
    data = json.loads(data)
    return data
    # print(data)
    # {
    #     'graph': [
    #         {'name': '招商中证白酒指数(LOF)A', 'valueField': '161725', 'lineColor': '#0099CC'}, 
    #         {'name': '南方全球精选配置', 'valueField': '202801', 'lineColor': '#FF0000'}], 
    #     'dataProvider': [
    #         {'date': '2023/04/04', '161725': 0.0, '202801': 'undefined'}, 
    #         {'date': '2023/04/06', '161725': -2.38, '202801': 0.0}, 
    #         {'date': '2023/04/07', '161725': -3.23, '202801': -0.68}, 
    #         {'date': '2023/04/10', '161725': -4.78, '202801': -0.57}, 
    #         {'date': '2023/04/11', '161725': -6.55, '202801': -0.68}, 
    #         {'date': '2023/04/12', '161725': -8.76, '202801': 0.34}, 
    #         {'date': '2023/04/13', '161725': -7.88, '202801': -0.34},
    #         {'date': '2023/04/14', '161725': -9.09, '202801': 0.34},
    #         {'date': '2023/04/17', '161725': -7.61, '202801': 0.11},
    #         {'date': '2023/04/18', '161725': -7.48, '202801': 0.68},
    #         {'date': '2023/04/19', '161725': -8.04, '202801': 0.68},
    #         {'date': '2023/04/20', '161725': -9.26, '202801': -0.23}, 
    #         {'date': '2023/04/21', '161725': -9.84, '202801': -0.23}, 
    #         {'date': '2023/04/24', '161725': -11.48, '202801': -1.59}, 
    #         {'date': '2023/04/25', '161725': -10.21, '202801': -1.59}, 
    #         {'date': '2023/04/26', '161725': -10.21, '202801': -3.3}, 
    #         {'date': '2023/04/27', '161725': -10.02, '202801': -2.73},
    #         {'date': '2023/04/28', '161725': -9.3, '202801': -2.16}, 
    #         {'date': '2023/05/04', '161725': -10.4, '202801': -1.59},
    #         {'date': '2023/05/05', '161725': -9.45, '202801': -3.18}]
    # }


if __name__ == "__main__":
    # print(search('fof'))
    # print(filter_())
    # detail("004243")
    # detail("110037")
    # get_picture("110037")
    # get_ljsylzs("005477")
    get_js_data("005477")
    # get_jbxx("161725,202801")
    # get_yjpjbj("161725,202801")
    # get_ljsyl("161725,202801")
